package com.coderman.utils.paramcheck;

import com.coderman.utils.error.CommonErrorEnum;
import com.coderman.utils.exceptions.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;

/**
 * @author shenshuai
 * @since 2020/1/7 5:55 下午
 */
public class ParamCheckUtil {

    /**
     * 校验请求参数是否为空
     *
     * @param requestParams 请求入参
     * @param keys          属性值数组
     */
    public static void checkParams(Object requestParams, String... keys) throws Exception {
        if (null == requestParams) {
            throw ExceptionUtils.error(CommonErrorEnum.REQUEST_OBJECT_IS_NULL_ERROR);
        }
        StringBuilder sb = new StringBuilder();
        for (String fieldName : keys) {
            Object value = null;
            Type type = null;
            try {
                String firstLetter = fieldName.substring(0, 1).toUpperCase();
                String getter = "get" + firstLetter + fieldName.substring(1);
                Method method = requestParams.getClass().getMethod(getter);
                value = method.invoke(requestParams);
                type = method.getReturnType();
            } catch (Exception e) {
                throw  ExceptionUtils.error(CommonErrorEnum.PARAMS_CANNOT_BE_NULL_ERROR,"获取属性值出错");
            } finally {
                // 判空标志 String/Collection/Map特殊处理
                boolean isEmpty =
                        (null == value) || (String.class == type && StringUtils.isEmpty((String) value))
                                || (value instanceof Collection  && ((Collection<? extends Object>) value).isEmpty())
                                || (Map.class == type && ((Map<? extends Object, ? extends Object>) value).isEmpty());
                if (isEmpty) {
                    if (sb.length() != 0) {
                        sb.append(",");
                    }
                    sb.append(fieldName);
                }
            }
        }

        if (sb.length() > 0) {
            throw  ExceptionUtils.error(CommonErrorEnum.PARAMS_CANNOT_BE_NULL_ERROR);
        }
    }
}
